package com.example.treasure_back;

import com.example.treasure_back.entity.BusinessException;
import com.example.treasure_back.entity.MsgEntity;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.mail.MessagingException;
import java.io.IOException;

@ControllerAdvice
@ResponseBody
public class ControllerExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public MsgEntity businessExceptionHandle(BusinessException ex) {
        return new MsgEntity("ERROR", ex.getCode(),"Business execution failed: " + ex.getMessage());
    }

    @ExceptionHandler({MessagingException.class, IOException.class})
    public MsgEntity messagingExceptionHandler(){
        return new MsgEntity("ERROR","-2","邮箱格式或输入错误");
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(value= HttpStatus.FORBIDDEN)
    public MsgEntity unauthorizedExceptionHandle(UnauthorizedException ex) {
        return new MsgEntity("ERROR","-1","Unauthorized: " + ex.getMessage());
    }
}
